package com.loren.demo11.interceptor;

import com.loren.demo11.wrapper.CustomHttpRequestWrapper;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class RetryClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    @NonNull
    @Override
    public ClientHttpResponse intercept(@NonNull HttpRequest request, @NonNull byte[] body, @NonNull ClientHttpRequestExecution execution) throws IOException {
        String requestUrl = request.getURI().toString();
        if (requestUrl.contains("?")) {
            requestUrl += "&access_token=123456";
        } else {
            requestUrl += "?access_token=123456";
        }
        CustomHttpRequestWrapper requestWrapper = new CustomHttpRequestWrapper(request, requestUrl);
        // 真正执行请求
        ClientHttpResponse response = execution.execute(requestWrapper, body);
        InputStream inputStream = response.getBody();
        String responseBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        System.out.println(responseBody);
        return response;
    }
}
